import * as signalR from "@microsoft/signalr";
import EventEmitter from "events"
import TypedEmitter from "typed-emitter"
export interface WsMessage {
  /**
   * 类型
   */
  type: string
  /**
   * 内容
   */
  content: string
}
export type MessageEvents = {
  /**
   * 连接建立时
   */
  onOpen(): any
  /**
   * 断连后重新连接
   */
  onReConnect(): any
  /**
   * 收到消息时
   * @param msg
   */
  onMessage(msg: WsMessage): any
  /**
   * 验证身份完成时
   */
  onAuthenticated(): any
  /**
   * 关闭时
   */
  onClose(): any

}

const messageEmitter = new EventEmitter() as TypedEmitter<MessageEvents>

/**
 * 防抖
 * @param fn 
 * @param delay 
 * @returns 
 */
function debounce(fn: Function, delay: number) {
  let timer: any = null //借助闭包
  return function () {
    if (timer) {
      clearTimeout(timer)
      timer = setTimeout(fn, delay)
    } else {
      timer = setTimeout(fn, delay)
    }
  }
}

const state = {
  ws: <any>null,
  connecting: false,
  enableLog: true
}

let host = ""
if (import.meta.env.DEV) {
  host = import.meta.env.VITE_WEB_SOCKET as string
} else {

  host = window.location.host + '/api/client/ws'
  if (window.location.href.startsWith("https")) {
    host = "wss://" + host
  } else {
    host = "ws://" + host
  }
}
let token = localStorage.getItem('jst:token')?.substring(7);
let inhost = host + '?access_token=' + token

/**
 * 防抖5秒等待 重连
 */
const reConnect = debounce(() => {
  initConnection(true);
}, 5000);

function initConnection(isReconnect: boolean = false) {
  state.ws = null
  state.ws = new signalR.HubConnectionBuilder()
    .withUrl(inhost)
    .withAutomaticReconnect()
    .build();
    
  state.ws.start().then((res: any) => {
    console.log("SignalR connected");
  }).catch((err: any) => {
    console.error("Error connecting to SignalR:", err.toString())
  });
  state.ws.on("ReceiveMessage", function (msg: any) {
    let message=JSON.parse(msg)
    console.log(message);
    messageEmitter.emit("onMessage", message)
  });
  state.ws.onclose((err: any) => {
    if (err) {
      console.log(err)
      console.error(`连接关闭时发生错误: ${err.toString}`);
    } else {
      console.log('连接已经关闭');
    }
    // reConnect();
  });
}

const sendMessage = (user: any, message: string) => {
  if (state.ws == null || state.connecting == false) {
    return
  }
  state.ws.invoke("SendMessage", user, message);
};

// const receiveMessage = (callback:Function) => {
//   state.ws.on("ReceiveMessage", (user, message) => {
//     callback(`${user}: ${message}`);
//   });
// };
initConnection()

export default {
  sendMessage,
  event: messageEmitter,
  // receiveMessage,
};